<script setup lang="ts">
defineOptions({
  name: "edit"
});
import { ref, reactive, computed, onMounted } from "vue";
import type { FormInstance, FormRules } from "px-ui";
import { batchUpdateDetectorLedger, updateDetectorLedger } from "@/api/modules/operation";
import { queryFileList } from "@/api/modules/fab";
import FileUpload from "@/components/Upload/FileUpload.vue";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

interface Props {
  batch?: boolean;
  gasName?: string;
  detectorCode?: string;
  ids?: Array<any>;
  calibrationDate?: string;
  calibrationDateHistory?: string;
  signCycle?: number;
  // timeLimit?: number | null;
  detectorCodeList?: Array<any>;
}

const props = withDefaults(defineProps<Props>(), {
  batch: false,
  gasName: "",
  detectorCode: "",
  ids: () => [],
  calibrationDate: "",
  calibrationDateHistory: "",
  signCycle: 0,
  // timeLimit: 0,
  detectorCodeList: () => []
});

const dialogTableVisible = defineModel({ type: Boolean, default: false });

const loading = ref<boolean>(false);
const title = computed(() => (props.batch ? "批量编辑" : "编辑"));
//  图片上传类型add：新增，edit：编辑，view：查看
const uploadType = ref<string>("add");
const fileList = ref<Array<any>>([]);
const isDeleteLocal = computed(() => !props.batch);

interface RuleForm {
  calibrationDate: string;
  signCycle: number;
  // timeLimit: number;
}
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  calibrationDate: "",
  signCycle: 0
  // timeLimit: 0
});

const rules = reactive<FormRules<RuleForm>>({
  calibrationDate: [{ required: false, message: "请选择标定/更换日期", trigger: "blur" }],
  signCycle: [{ required: false, message: "请选择标定/更换周期", trigger: "blur" }]
  // timeLimit: [{ required: false, message: "请输入提醒设置", trigger: "blur" }]
});

const emits = defineEmits(["submit"]);

const changeFileListHandler = (fl: Array<any>) => {
  fileList.value = [];
  if (!fl?.length) return;
  fileList.value = fl.map(item => item);
};

const cancelHandler = () => {
  dialogTableVisible.value = false;
};

const submitHandler = useThrottleFn(async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      loading.value = true;
      const fileIds = fileList.value?.map(item => item.id);
      const fileNameList = fileList.value?.map(item => item.originalName);
      const { batch = false, detectorCodeList = [], detectorCode = "", gasName = "" } = props;
      let params: Record<string, any> = { ...ruleForm };
      let res: any = null;
      if (batch) {
        params = { ...params, detectorCodeList, fileIds, fileNameList };
        res = await batchUpdateDetectorLedger(params, () => {
          loading.value = false;
        });
      } else {
        params = { ...params, detectorCode, gasName, fileIds, fileNameList };
        res = await updateDetectorLedger(params, () => {
          loading.value = false;
        });
      }
      loading.value = false;
      emits("submit");
      dialogTableVisible.value = false;
    } else {
      console.error("error submit!", fields);
    }
  });
}, delay);

const queryFileListFn = async () => {
  const { ids = [] } = props;
  if (!ids?.length) return;
  const params = { ids };
  loading.value = true;
  const res = await queryFileList(params, () => {
    loading.value = false;
  });
  loading.value = false;
  if (!res?.length) return;
  fileList.value = res;
};

const init = async () => {
  const { calibrationDate = "", signCycle = 0 } = props;
  if (!props.batch) {
    ruleForm.calibrationDate = calibrationDate;
    ruleForm.signCycle = signCycle;
    // ruleForm.timeLimit = timeLimit;
    await queryFileListFn();
  }
};

onMounted(async () => {
  await init();
});
</script>

<template>
  <px-dialog v-model="dialogTableVisible" :title="title" width="1000px">
    <px-form ref="ruleFormRef" v-loading="loading" :model="ruleForm" :rules="rules" inline label-width="130px" status-icon>
      <px-row :gutter="24">
        <px-col :span="12">
          <px-form-item label="标定/更换日期" prop="calibrationDate">
            <px-date-picker
              v-model="ruleForm.calibrationDate"
              clearable
              type="date"
              :editable="false"
              format="YYYY/MM/DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择标定/更换日期"
            />
          </px-form-item>
        </px-col>

        <px-col :span="12">
          <px-form-item label="标定/更换周期" prop="signCycle">
            <px-input
              v-model.trim.number="ruleForm.signCycle"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入标定/更换周期"
            />
          </px-form-item>
        </px-col>

        <!-- <px-col :span="8">
          <px-form-item label="提醒设置" prop="timeLimit">
            <px-input
              v-model.trim.number="ruleForm.timeLimit"
              class="px-input-number-no-controls"
              type="number"
              clearable
              :min="0"
              placeholder="请输入提醒设置"
            />
          </px-form-item>
        </px-col> -->

        <px-col v-if="!batch" :span="24">
          <px-form-item label="历史标定/更换日期" prop="">
            <div>{{ calibrationDateHistory || "--" }}</div>
          </px-form-item>
        </px-col>

        <px-col :span="24">
          <px-form-item label="上传文档" prop="fileIdList" class="item-upload">
            <FileUpload
              :multiple="false"
              :isDeleteLocal="isDeleteLocal"
              :fileType="uploadType"
              :fileList="fileList"
              :countLimit="5"
              @changeFileList="changeFileListHandler"
            />
          </px-form-item>
        </px-col>
      </px-row>
    </px-form>
    <template #footer>
      <span class="dialog-footer">
        <px-button @click="cancelHandler">取消</px-button>
        <px-button type="primary" :loading="loading" @click="submitHandler"> 确认 </px-button>
      </span>
    </template>
  </px-dialog>
</template>

<style lang="scss" scoped>
:deep(.px-form-item) {
  width: 100%;

  .item-upload {
    .px-form-item__content {
      margin-left: 0 !important;
    }
  }

  .px-form-item__content {
    .px-input-number .px-input__inner {
      text-align: left;
    }

    .px-input,
    .px-input-number,
    .px-time-picker {
      width: 100%;
    }
  }
}
</style>
